<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px">
      <el-form-item label="区域" prop="areaId">
        <el-tree-select
          v-model="searchSelectedAreaId"
          :data="searchAreaOptions"
          :props="{ value: 'id', label: 'name', children: 'childs' }"
          value-key="id"
          placeholder="请选择区域/楼宇/单元"
          check-strictly
          style="width: 240px"
          default-expand-all
          clearable
          @change="handleSearchAreaChange"
        />
      </el-form-item>
      <el-form-item label="证件类型" prop="idType">
        <el-select
          v-model="queryParams.idType"
          placeholder="请选择证件类型"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in idTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="recordStatus">
        <el-select
          v-model="queryParams.recordStatus"
          placeholder="请选择审核状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in recordStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['pms:record:add']" type="primary" plain icon="Plus" @click="handleAdd">新增投票记录</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table border v-loading="loading" :data="votingRecordsList">
      <el-table-column label="房号" min-width="250" align="center" prop="roomCode">
        <template #default="scope">
          <div v-if="scope.row.houseDtos && scope.row.houseDtos.length > 0" style="text-align: left;">
            <!-- 显示前两个房屋 -->
            <div 
              v-for="(house, index) in scope.row.houseDtos.slice(0, 2)" 
              :key="index"
              style="padding: 2px 0;"
              :style="{ borderBottom: index < 1 && scope.row.houseDtos.length > 1 ? '1px dashed #eee' : 'none' }"
            >
              <span style="color: #606266;">
                {{ getHouseFullAddress(house) }}
              </span>
            </div>
            <!-- 超过两个显示"查看更多"按钮 -->
            <el-button 
              v-if="scope.row.houseDtos.length > 2" 
              type="primary" 
              link 
              size="small"
              style="margin-top: 4px;"
              @click="showMoreHouses(scope.row)"
            >
              查看更多({{ scope.row.houseDtos.length }}个)
            </el-button>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="投票人" align="center" prop="voteName" />
      <el-table-column label="标识" align="center" prop="recordCode"  min-width="200">
        <template #default="scope">
          <span>{{ scope.row.pmsVoteRecord.recordCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" min-width="100" align="center" prop="recordStatus" >
        <template #default="scope">
          <span>{{ getRecordStatusName(scope.row.pmsVoteRecord.recordStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" min-width="150" align="center" prop="mobile" />
      <el-table-column label="证件类型"  min-width="150" align="center" prop="idType">
        <template #default="scope">
          <span>{{ getIdTypeName(scope.row.pmsVoteRecord.idType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="证件号码" min-width="200"  align="center" prop="idNum" >
        <template #default="scope">
          <span>{{ scope.row.pmsVoteRecord.idNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投票选项"  min-width="150" align="center" prop="voteOption" >
        <template #default="scope">
          <span>{{ Array.isArray(scope.row.voteOption) ? scope.row.voteOption.join(', ') : scope.row.voteOption }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投票图片" align="center" prop="votePicUrl" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.votePicUrl"
            :src="scope.row.votePicUrl"
             :preview-teleported="true"
            style="width: 50px; height: 50px"
            :preview-src-list="[scope.row.pmsVoteRecord.votePicUrl?scope.row.pmsVoteRecord.votePicUrl.split(',') : []]"
            fit="cover"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
    
    
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.createDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button 
            v-if="scope.row.pmsVoteRecord.recordStatus === 0"
            v-hasPermi="['pms:record:edit']"
            link 
            type="primary" 
            icon="Check" 
            @click="handleAudit(scope.row)"
          >
            审核
          </el-button>
          <el-button 
            v-if="isDevelopment"
            type="danger" 
            link 
            icon="Delete" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>

        <!-- <el-button type="primary" link icon="Edit" @click="handleEdit(scope.row)">编辑</el-button> -->
       
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增投票记录弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增投票记录"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="选择区域:" prop="selectedAreaId">
              <el-tree-select
                v-model="selectedAreaId"
                :data="areaOptions"
                :props="{ value: 'id', label: 'name', children: 'childs' }"
                value-key="id"
                placeholder="请选择区域"
                check-strictly
                style="width: 100%"
                default-expand-all
                @change="handleAreaChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="房屋选择:" prop="houseId">
              <el-select
                v-model="addForm.houseId"
                placeholder="请选择房屋"
                style="width: 100%"
                filterable
                @change="handleHouseChange"
              >
                <el-option
                  v-for="item in houseOptions"
                  :key="item.pmsHouse.houseId"
                  :label="`${item.pmsHouse.roomCode} - ${item.pmsHouseBindUsers?.[0]?.name || '无产权人'}`"
                  :value="item.pmsHouse.houseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="投票人姓名:" prop="voteName">
              <el-input
                v-model="addForm.voteName"
                placeholder="请输入投票人姓名"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标识:" prop="recordCode">
              <el-input
                v-model="addForm.recordCode"
                placeholder="请输入标识"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号:" prop="mobile">
              <el-input
                v-model="addForm.mobile"
                placeholder="请输入手机号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证件类型:" prop="idType">
              <el-select
                v-model="addForm.idType"
                placeholder="请选择证件类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in idTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="证件号码:" prop="idNum">
              <el-input
                v-model="addForm.idNum"
                placeholder="请输入证件号码"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="投票图片:" prop="votePicUrl">
              <ImageUpload
                v-model="addForm.votePicUrl"
                :limit="1"
                :file-size="5"
                :file-type="['png', 'jpg', 'jpeg']"
              />
            </el-form-item>
          </el-col>
          
          <!-- 多问题投票选项 -->
          <el-col :span="24">
            <el-form-item label="投票选项:" prop="voteAnswers">
              <div v-if="voteQuestions.length > 0" style="width: 100%;">
                <div v-for="(question, qIdx) in voteQuestions" :key="qIdx" style="margin-bottom: 20px;">
                  <el-card shadow="never" style="border-radius: 8px; border: 1px solid #e4e7ed;">
                    <div style="margin-bottom: 16px;">
                      <div style="font-weight: bold; color: #333; margin-bottom: 8px;">
                        问题 {{ qIdx + 1 }}: {{ question.title }}
                      </div>
                      <div style="color: #666; font-size: 12px;">
                        类型: {{ question.optionType === 1 ? '单选' : '多选' }}
                        <span v-if="question.optionType === 2 && shouldShowLimitHint(question)" style="margin-left: 10px;">
                          {{ getLimitHintText(question) }}
                        </span>
                      </div>
                    </div>
                    
                    <!-- 单选 -->
                    <el-radio-group
                      v-if="question.optionType === 1"
                      v-model="addForm.voteAnswers[qIdx]"
                      @change="handleQuestionAnswerChange(qIdx, $event)"
                    >
                      <el-radio
                        v-for="option in question.options"
                        :key="option.optionId"
                        :label="option.optionId"
                        style="display: block; margin-bottom: 10px;"
                      >
                        {{ option.name }}
                      </el-radio>
                    </el-radio-group>
                    
                    <!-- 多选 -->
                    <el-checkbox-group 
                      v-else-if="question.optionType === 2" 
                      v-model="addForm.voteAnswers[qIdx]"
                      @change="handleQuestionAnswerChange(qIdx, $event)"
                    >
                      <el-checkbox
                        v-for="option in question.options"
                        :key="option.optionId"
                        :label="option.optionId"
                        :disabled="isOptionDisabled(qIdx, option.optionId)"
                        style="display: block; margin-bottom: 10px;"
                      >
                        {{ option.name }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-card>
                </div>
              </div>
              <!-- 未加载投票信息时显示 -->
              <div v-else style="color: #999; text-align: center; padding: 20px;">
                正在加载投票选项...
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看更多房屋弹窗 -->
    <el-dialog
      v-model="moreHousesDialogVisible"
      title="关联房屋列表"
      width="600px"
    >
      <div style="max-height: 400px; overflow-y: auto;">
        <el-table :data="currentHouseList" border stripe>
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="房屋地址" align="left">
            <template #default="scope">
              <span style="color: #606266;">{{ getHouseFullAddress(scope.row) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="moreHousesDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { listHouse,listVotingRecords, deleteVotingRecords, addVotingRecords, getVoteDetail, auditVotingRecord } from '@/api/house/votingrecords';

import { listArea } from '@/api/house/area';
import { useRoute } from 'vue-router';
import { ElMessage,ElMessageBox } from 'element-plus';
import ImageUpload from '@/components/ImageUpload/index.vue';

const route = useRoute();
const voteId = route.query.voteId;

const { proxy } = getCurrentInstance();

// 判断是否为开发环境
const isDevelopment = import.meta.env.MODE === 'development';

// 证件类型选项
const idTypeOptions = [
  { label: '居民身份证', value: 1 },
  { label: '护照', value: 2 },
  { label: '居住证', value: 3 }
];

// 审核状态选项
const recordStatusOptions = [
  { label: '待审核', value: 0 },
  { label: '已审核', value: 1 }
];

const loading = ref(true);
const votingRecordsList = ref([]);
const total = ref(0);

// 查看更多房屋弹窗
const moreHousesDialogVisible = ref(false);
const currentHouseList = ref([]);
const houseOptions = ref([]);
const areaOptions = ref([]);
const searchAreaOptions = ref([]); // 搜索用的区域选项
const selectedAreaId = ref('');
const searchSelectedAreaId = ref(''); // 搜索用的选中区域ID
const dialogVisible = ref(false);
const submitLoading = ref(false);

// 投票相关数据
const voteInfo = ref({});
const pmsVoteOptions = ref([]);
const voteQuestions = ref([]); // 新增：按问题分组的投票选项

// 定义区域ID键常量
const AREA_ID_KEYS = ['areaId', 'buildId', 'unitId'];

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    voteId: undefined,
    liveUserId: undefined,
    houseId: undefined,
    createDate: undefined,
    areaId: undefined, // 搜索区域ID
    buildId: undefined, // 搜索楼宇ID
    unitId: undefined, // 搜索单元ID
    idType: undefined, // 搜索证件类型
    recordStatus: undefined, // 搜索审核状态
  }
});

// 新增表单数据
const addForm = reactive({
  houseId: '',
  voteName: '',
  mobile: '',
  voteAnswers: [], // 修改：存储每个问题的答案
  areaId: '',
  buildId: '',
  unitId: '',
  idType: '',
  idNum: '',
  votePicUrl: '',
  recordCode: ''
});

// 表单验证规则
const addFormRules = {
  houseId: [
    { required: true, message: '请选择房屋', trigger: 'change' }
  ],
  voteName: [
    { required: true, message: '请输入投票人姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idType: [
    { required: true, message: '请选择证件类型', trigger: 'change' }
  ],
  idNum: [
    { required: true, message: '请输入证件号码', trigger: 'blur' }
  ],
  voteAnswers: [
    { 
      required: true, 
      message: '请完成所有问题的投票', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!value || value.length !== voteQuestions.value.length) {
          callback(new Error('请完成所有问题的投票'));
          return;
        }
        
        // 检查每个问题是否都有答案
        for (let i = 0; i < value.length; i++) {
          const question = voteQuestions.value[i];
          const answer = value[i];
          const limit = getQuestionSelectionLimit(question);
          
          if (question.optionType === 1) {
            // 单选：答案应该是单个值
            if (!answer) {
              callback(new Error(`请回答问题${i + 1}`));
              return;
            }
          } else if (question.optionType === 2) {
            // 多选：答案应该是数组，并检查最小选择限制
            if (!Array.isArray(answer) || answer.length === 0) {
              callback(new Error(`请回答问题${i + 1}`));
              return;
            }
            
            // 检查最小选择数量
            const minRequired = Math.max(limit.min, 1);
            if (answer.length < minRequired) {
              callback(new Error(`问题${i + 1}至少需要选择${minRequired}个选项`));
              return;
            }
            
            // 检查最大选择数量
            if (answer.length > limit.max) {
              callback(new Error(`问题${i + 1}最多只能选择${limit.max}个选项`));
              return;
            }
          }
        }
        callback();
      }
    }
  ],
  recordCode: [
    { required: true, message: '请输入标识', trigger: 'blur' }
  ]
};

const { queryParams } = toRefs(data);
const queryRef = ref(null);
const addFormRef = ref(null);

// 格式化区域树数据
function normalizeAreaTree(data, parentLevel = 0) {
  return data.map(area => {
    const level = parentLevel + 1;
    const areaNode = {
      ...area,
      id: area.areaId,
      level,
      childs: []
    };
    if (Array.isArray(area.pmsBuilds)) {
      areaNode.childs = area.pmsBuilds.map(build => {
        const buildNode = {
          ...build,
          id: build.id,
          level: level + 1,
          childs: []
        };
        if (Array.isArray(build.units)) {
          buildNode.childs = build.units.map(unit => ({
            ...unit,
            id: unit.id,
            level: level + 2,
            areaId: area.areaId,
            buildId: build.id,
            childs: []
          }));
        }
        return buildNode;
      });
    }
    return areaNode;
  });
}

// 根据ID查找节点
function findNodeById(tree, targetId) {
  for (const node of tree) {
    if (node.id === targetId) {
      return node;
    }
    if (node.childs && node.childs.length) {
      const result = findNodeById(node.childs, targetId);
      if (result) return result;
    }
  }
  return null;
}

// 搜索区域变化处理
function handleSearchAreaChange(value) {
  console.log('搜索区域变化:', value);
  
  // 清空所有层级ID
  queryParams.value.areaId = undefined;
  queryParams.value.buildId = undefined;
  queryParams.value.unitId = undefined;
  
  if (value) {
    // 根据选中的节点类型设置对应的字段
    const selectedNode = findNodeById(searchAreaOptions.value, value);
    if (selectedNode) {
      console.log('选中的搜索节点:', selectedNode);

      if (selectedNode.level === 1) {
        // 区域节点：只设置areaId
        queryParams.value.areaId = selectedNode.areaId;
      } else if (selectedNode.level === 2) {
        // 楼宇节点：设置areaId和buildId
        queryParams.value.areaId = selectedNode.areaId;
        queryParams.value.buildId = selectedNode.id;
      } else if (selectedNode.level === 3) {
        // 单元节点：设置areaId、buildId和unitId
        queryParams.value.areaId = selectedNode.areaId;
        queryParams.value.buildId = selectedNode.buildId;
        queryParams.value.unitId = selectedNode.id;
      }
      console.log("搜索参数", queryParams.value);
    }
  }
}

// 初始化搜索区域数据
function initSearchAreaData() {
  listArea({ pageNum: 1, pageSize: 1000, status: 1 }).then(res => {
    const normalizedData = normalizeAreaTree(res?.rows || []);
    searchAreaOptions.value = normalizedData;
  }).catch(error => {
    console.error('获取搜索区域数据失败:', error);
    ElMessage.error('获取搜索区域数据失败，请稍后重试');
  });
}

// 证件类型名称转换
function getIdTypeName(idType) {
  const typeOption = idTypeOptions.find(item => item.value === idType);
  return typeOption ? typeOption.label : '-';
}

// 审核状态名称转换
function getRecordStatusName(status) {
  const statusOption = recordStatusOptions.find(item => item.value === status);
  return statusOption ? statusOption.label : '-';
}

// 拼接完整房屋地址
function getHouseFullAddress(house) {
  if (!house) return '-'
  
  const parts = []
  
  // 从 areaInfo 或单独字段获取区域、栋、单元信息
  if (house.areaName) parts.push(house.areaName)
  if (house.buildName) parts.push(house.buildName)
  if (house.unitName) parts.push(house.unitName)
  
  // 添加房间号
  if (house.pmsHouse?.roomCode) {
    parts.push(house.pmsHouse.roomCode)
  } else if (house.roomCode) {
    parts.push(house.roomCode)
  }
  
  return parts.length > 0 ? parts.join('-') : '-'
}

// 显示更多房屋
function showMoreHouses(row) {
  if (row.houseDtos && row.houseDtos.length > 0) {
    currentHouseList.value = row.houseDtos;
    moreHousesDialogVisible.value = true;
  }
}

// 区域选择变化处理
function handleAreaChange(value) {
  console.log('选中的节点ID:', value);

  // 清空所有层级ID和房屋选项
  AREA_ID_KEYS.forEach(key => {
    addForm[key] = '';
  });
  addForm.houseId = '';
  houseOptions.value = [];

  if (value) {
    // 根据选中的节点类型设置对应的字段
    const selectedNode = findNodeById(areaOptions.value, value);
    if (selectedNode) {
      console.log('选中的节点:', selectedNode);

      if (selectedNode.level === 1) {
        // 区域节点：只设置areaId
        addForm.areaId = selectedNode.areaId;
        // 调用接口获取房屋数据
        loadHouseData({ areaId: selectedNode.areaId });
      } else if (selectedNode.level === 2) {
        // 楼宇节点：设置areaId和buildId
        addForm.areaId = selectedNode.areaId;
        addForm.buildId = selectedNode.id;
        // 调用接口获取房屋数据
        loadHouseData({ areaId: selectedNode.areaId, buildId: selectedNode.id });
      } else if (selectedNode.level === 3) {
        // 单元节点：设置areaId、buildId和unitId
        addForm.areaId = selectedNode.areaId;
        addForm.buildId = selectedNode.buildId;
        addForm.unitId = selectedNode.id;
        // 调用接口获取房屋数据
        loadHouseData({ areaId: selectedNode.areaId, buildId: selectedNode.buildId, unitId: selectedNode.id });
      }
      console.log("addForm", addForm);
    }
  }
}

// 加载房屋数据
function loadHouseData(params) {
  const requestParams = {
  
    pageNum: 1,
    pageSize: 1000,
    voteId:voteId,
    voteStatue:2,
    ...params
  };
  
  console.log('请求房屋数据参数:', requestParams);
  
  listHouse(requestParams).then(res => {
    if (res.code === 200) {
      houseOptions.value = res.rows || [];
      console.log('房屋数据:', houseOptions.value);
    } else {
      console.error('获取房屋数据失败:', res.msg);
      ElMessage.error('获取房屋数据失败');
    }
  }).catch(error => {
    console.error('获取房屋数据失败:', error);
    ElMessage.error('获取房屋数据失败，请稍后重试');
  });
}

// 获取投票详情 - 修改为按问题分组
async function getVoteDetailData() {
  try {
    const response = await getVoteDetail({
      voteId: voteId,
    });
    
    if (response.code === 200) {
      const data = response.data;
      voteInfo.value = data.pmsVote || {};
      pmsVoteOptions.value = data.pmsVoteOptions || [];
      
      // 按问题分组投票选项
      const questionMap = new Map();
      pmsVoteOptions.value.forEach(option => {
        if (option.title) {
          if (!questionMap.has(option.title)) {
            questionMap.set(option.title, {
              title: option.title,
              optionType: option.optionType || 1,
              minNum: option.minNum || 0,
              maxNum: option.maxNum || 999,
              remark: option.remark || '',
              options: []
            });
          }
          questionMap.get(option.title).options.push(option);
        }
      });
      
      voteQuestions.value = Array.from(questionMap.values());
      
      // 初始化答案数组
      addForm.voteAnswers = voteQuestions.value.map(question => {
        return question.optionType === 1 ? '' : []; // 单选初始化为空字符串，多选初始化为空数组
      });
      
      console.log('投票信息:', voteInfo.value);
      console.log('投票问题:', voteQuestions.value);
    } else {
      ElMessage.error(response.msg || '获取投票详情失败');
    }
  } catch (error) {
    console.error('获取投票详情失败:', error);
    ElMessage.error('获取投票详情失败，请稍后重试');
  }
}

// 问题答案变化处理
function handleQuestionAnswerChange(questionIndex, value) {
  console.log(`问题${questionIndex + 1}答案变化:`, value);
  const question = voteQuestions.value[questionIndex];
  
  // 多选时检查选择限制
  if (question.optionType === 2 && Array.isArray(value)) {
    const limit = getQuestionSelectionLimit(question);
    
    // 检查最大选择数量
    if (value.length > limit.max) {
      ElMessage.warning(`该问题最多只能选择${limit.max}个选项`);
      // 保持之前的选择，不更新
      return;
    }
  }
  
  addForm.voteAnswers[questionIndex] = value;
}

// 房屋选择变化处理
function handleHouseChange(value) {
  console.log('选中的房屋ID:', value);
  const selectedHouse = houseOptions.value.find(item => item.pmsHouse.houseId === value);
  if (selectedHouse) {
    addForm.voteName = selectedHouse.pmsHouseBindUsers?.[0]?.name || '';
    addForm.mobile = selectedHouse.pmsHouseBindUsers?.[0]?.mobile || '';
    console.log('自动填充的投票人信息:', addForm);
  } else {
    // 如果没有找到对应的房屋，清空投票人信息
    addForm.voteName = '';
    addForm.mobile = '';
    console.log('清空投票人信息');
  }
}

// 新增按钮点击
function handleAdd() {
  dialogVisible.value = true;
  // 重置表单
  resetForm();
  
  // 加载区域数据
  if (areaOptions.value.length === 0) {
    listArea({ pageNum: 1, pageSize: 1000, status: 1 }).then(res => {
      const normalizedData = normalizeAreaTree(res?.rows || []);
      areaOptions.value = normalizedData;
    }).catch(error => {
      console.error('获取区域数据失败:', error);
      ElMessage.error('获取区域数据失败，请稍后重试');
    });
  }
  
  // 获取投票详情
  getVoteDetailData();
}

// 重置表单
function resetForm() {
  // 重置表单数据
  Object.keys(addForm).forEach(key => {
    if (key === 'voteAnswers') {
      // 根据问题数量初始化答案数组
      addForm[key] = voteQuestions.value.map(question => {
        return question.optionType === 1 ? '' : [];
      });
    } else {
      addForm[key] = '';
    }
  });
  
  // 重置区域选择
  selectedAreaId.value = '';
  houseOptions.value = [];
  
  // 重置表单验证状态
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
}

// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      
      // 处理投票选项数据 - 根据答案构建选项列表
      let optionList = [];
      addForm.voteAnswers.forEach((answer, questionIndex) => {
        const question = voteQuestions.value[questionIndex];
        
        if (question.optionType === 1) {
          // 单选：找到对应的选项
          const option = question.options.find(opt => opt.optionId === answer);
          if (option) {
            optionList.push(option);
          }
        } else if (question.optionType === 2) {
          // 多选：找到所有对应的选项
          if (Array.isArray(answer)) {
            answer.forEach(optionId => {
              const option = question.options.find(opt => opt.optionId === optionId);
              if (option) {
                optionList.push(option);
              }
            });
          }
        }
      });
      
      const formData = {
        voteId: voteId,
        houseId: addForm.houseId,
        voterName: addForm.voteName,
        voterMobile: addForm.mobile,
        optionList: optionList,
        areaId: addForm.areaId,
        buildId: addForm.buildId,
        unitId: addForm.unitId,
        idType: addForm.idType,
        idNum: addForm.idNum,
        votePicUrl: addForm.votePicUrl,
        recordType: 2,
        recordCode: addForm.recordCode
      };

      console.log('提交的表单数据:', formData);

      addVotingRecords(formData).then(response => {
        if (response.code === 200) {
          ElMessage.success('新增成功');
          dialogVisible.value = false;
          resetForm();
          getList();
        } else {
          ElMessage.error(response.msg || '新增失败');
        }
      }).catch(error => {
        ElMessage.error('网络错误，请稍后重试');
        console.error('提交失败:', error);
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

// 取消按钮点击
function handleCancel() {
  dialogVisible.value = false;
  resetForm(); // 取消时重置表单
}

// 审核投票记录
function handleAudit(row) {
  ElMessageBox.confirm('确认审核通过该投票记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const auditData = {
      recordId: row.pmsVoteRecord.recordId,
      recordStatus: 1
    };
    
    auditVotingRecord(auditData).then(response => {
      if (response.code === 200) {
        ElMessage.success('审核成功');
        getList(); // 刷新列表
      } else {
        ElMessage.error(response.msg || '审核失败');
      }
    }).catch(error => {
      ElMessage.error('网络错误，请稍后重试');
      console.error('审核失败:', error);
    });
  }).catch(() => {
    // 用户取消审核
  });
}

function handleEdit(row) {
  console.log(row);
}

function handleDelete(row) {
  deleteVotingRecords(row.recordId).then(response => {
    ElMessage.success('删除成功');
    getList();
  });
}

/** 查询投票记录列表 */
function getList() {
  console.log("voteId",voteId)
  loading.value = true;
  listVotingRecords({...queryParams.value,voteId:voteId,}).then(response => {
    votingRecordsList.value = response.rows.map(item => {
      console.log("item",item)
      item.votePicUrl=""
      if(item.pmsVoteRecord.votePicUrl){
        item.votePicUrl=item.pmsVoteRecord.votePicUrl.split(',')
        console.log("item.votePicUrl",item.votePicUrl)
      }
      // 处理投票选项，如果是JSON字符串则解析
      if (typeof item.voteOption === 'string') {
        try {
          item.voteOption = JSON.parse(item.voteOption)
        } catch (e) {
          // 如果解析失败，保持原值
          console.warn('投票选项解析失败:', item.voteOption)
        }
      }
      return item
    })
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询房屋列表 */
function getHouseList() {
  listHouse({ pageNum: 1, pageSize: 1000 }).then(response => {
    houseOptions.value = response.rows;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields();
  // 手动重置搜索条件
  queryParams.value.areaId = undefined;
  queryParams.value.buildId = undefined;
  queryParams.value.unitId = undefined;
  queryParams.value.idType = undefined;
  queryParams.value.recordStatus = undefined; // 重置审核状态
  searchSelectedAreaId.value = ''; // 重置搜索区域选择器
  handleQuery();
}

// 获取问题的选择限制
function getQuestionSelectionLimit(question) {
  return {
    min: question.minNum || 0,
    max: question.maxNum || 999
  };
}

// 判断选项是否应该被禁用（多选达到最大限制时）
function isOptionDisabled(questionIndex, optionId) {
  const question = voteQuestions.value[questionIndex];
  if (question.optionType !== 2) return false; // 单选不禁用
  
  const currentAnswers = addForm.voteAnswers[questionIndex] || [];
  const limit = getQuestionSelectionLimit(question);
  
  // 如果已选中该选项，不禁用（允许取消选择）
  if (currentAnswers.includes(optionId)) {
    return false;
  }
  
  // 如果已达到最大选择数量，禁用未选中的选项
  return currentAnswers.length >= limit.max;
}

// 判断是否应该显示限制提示
function shouldShowLimitHint(question) {
  if (question.optionType !== 2) return false; // 单选不显示
  
  const limit = getQuestionSelectionLimit(question);
  const minRequired = Math.max(limit.min, 1);
  
  // 如果min=1且max=999，表示只有基础限制，不显示提示
  if (minRequired === 1 && limit.max === 999) {
    return false;
  }
  
  return true;
}

// 获取限制提示文本
function getLimitHintText(question) {
  const limit = getQuestionSelectionLimit(question);
  const minRequired = Math.max(limit.min, 1);
  
  // 固定数量
  if (minRequired === limit.max) {
    return `（固定选择${minRequired}个）`;
  }
  
  // 只有下限
  if (minRequired > 1 && limit.max === 999) {
    return `（至少选择${minRequired}个）`;
  }
  
  // 只有上限
  if (minRequired === 1 && limit.max < 999) {
    return `（最多选择${limit.max}个）`;
  }
  
  // 有下限和上限
  if (minRequired > 1 && limit.max < 999) {
    return `（${minRequired}-${limit.max}个）`;
  }
  
  return '';
}

onMounted(() => {
  getList();
  // getHouseList();
  initSearchAreaData(); // 初始化搜索区域数据
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
